/**
 * PackDataMonitorServiceImpl.java
 * Created at 2017-2-20
 * Created by shihui
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.monitor.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import ws.org.tempuri.SaveMsgDataClient;

import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.bean.FileBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.repository.EntityDao;
import com.broadtext.common.service.impl.EntityServiceImpl;
import com.broadtext.common.utils.BaiduAPI;
import com.broadtext.common.utils.ExportThread;
import com.broadtext.common.utils.StrUtil;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.common.utils.ZipUtils;
import com.broadtext.rms.monitor.dao.ITtPackDao;
import com.broadtext.rms.monitor.model.FenceGpsInfo;
import com.broadtext.rms.monitor.model.HistoryQueryView;
import com.broadtext.rms.monitor.model.PackLocationInfo;
import com.broadtext.rms.monitor.model.PackRunTimeSpan;
import com.broadtext.rms.monitor.model.TtCellvoltageCurrent;
import com.broadtext.rms.monitor.model.TtPack;
import com.broadtext.rms.monitor.model.TtPackAlert;
import com.broadtext.rms.monitor.model.TtPackCurrent;
import com.broadtext.rms.monitor.service.IPackDataMonitorService;
import com.broadtext.rms.monitor.thread.QueryThread;
import com.broadtext.rms.system.dao.ISysDictDao;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: PackDataMonitorServiceImpl</p>
 * <p>Description: 电池监控服务层</p>
 * <p>Author: shihui</p>
 * <p>Date: 2017-2-20</p>
 */
@Service("packDataMonitorService")
public class PackDataMonitorServiceImpl extends EntityServiceImpl<TtPack> implements IPackDataMonitorService {

    /**
     * 处理标识： 已处理
     */
    private static final String HANDLED = "1";
    
    /**
     * 处理标识： 无需处理
     */
    private static final String UNNEED_HANDLED = "9";
    
    /**
     * 结果信息标识
     */
    private static final String MSG = "msg";
    
    /**
     * 历史表modelName
     */
    private static final String HISTORY_MODEL_NAME = "com.broadtext.rms.monitor.model.TtPackHis";
    
    /**
     * 注入电池监控Dao
     */
    @Autowired
    @Qualifier("ttPackDao")
    private ITtPackDao ttPackDao;
    
    /**
     * 注入字典Dao
     */
    @Autowired
    @Qualifier("sysDictDao")
    private ISysDictDao sysDictDao;
    
    @Autowired
    @Qualifier("ttPackDao")
    public void setEntityDao(EntityDao<TtPack> entityDao) {
        super.entityDao = entityDao;
    }
    
    /**
     * 
     * <p>Description: 按条件查询所有电池监控数据</p>
     * @param map 查询条件
     * @param pageBounds 翻页
     * @return 查询结果
     * @throws ServiceException 异常
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public EntityPageBean<Object> findPackMonitor(Map<String, Object> map, PageBounds pageBounds)
        throws ServiceException {
        EntityPageBean pb;
        pb = new EntityPageBean();
        try {
            pb = this.ttPackDao.findPackMonitorData(map, pageBounds);
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return pb;
    }

    /**
     * 
     * <p>Description: 将电池置为失效</p>
     * @param packIdArray 电池ID
     * @param parMap 更新参数
     * @return 操作结果
     * @throws ServiceException 异常
     */
    @Override
    public Map<String, Object> setPackUnenable(String[] packIdArray, Map<String, Object> parMap)
        throws ServiceException {
        TtPack pack;
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        for (String id : packIdArray) {
            pack = super.findEntityById(id);
            if (pack != null) {
                pack.setEnableFalg("0");
                pack.setUpdateDate(new Date());
                pack.setUpdateUser(parMap.get("sysName").toString());
                super.updateRecord(pack);
            } else {
                map.put(MSG, "error");
                return map;
            }
        }
        map.put(MSG, true);
        return map; 
    }
    
    /**
     * 
     * <p>Description: 根据条件查询监控电池当前实时信息</p>
     * @param entity 实体   
     * @return 结果集
     * @throws DaoException 异常
     */
    public Map<String, Object> getMonitorDataInfoCurrent(TtPackCurrent entity) throws DaoException {
        Map<String, Object> map;
        map = this.ttPackDao.getMonitorDataInfoCurrent(
                "com.broadtext.rms.monitor.model.TtPackCurrent.getMonitorDataInfoCurrent", entity);
        //调用百度api 解析经纬度为实际地理位置
        if (null != map && !map.isEmpty()) {
            //查询上电掉电状态
            /*List<PackRunTimeSpan> runTimeSpanList;
            runTimeSpanList = this.ttPackDao.getCurrentRuntimeSpanList(
                    "com.broadtext.rms.monitor.model.TtPackCurrent.getCurrentRuntimeSpanList", entity);*/
            /*if(null != runTimeSpanList && !runTimeSpanList.isEmpty()){
                //存在记录 
                if(runTimeSpanList.get(0).getEndTime() == null){
                    //最新记录不存在掉电状态 
                    map.put("POWER_ON_STATUS", "上电");
                } else {
                    //最新记录存在掉电状态 
                    map.put("POWER_ON_STATUS", "下电");
                    map.put("RUN_STATUS", "否");
                }
            } else {
                //不存在记录  上电状态
                map.put("POWER_ON_STATUS", "下电");
                map.put("RUN_STATUS", "否");
            }*/
            Map<String,Object> queryMap = new HashMap<String, Object>();
            queryMap.put("packCode", entity.getPackCode());
            queryMap.put("clientId", entity.getColClientId());
            Map<String,Object> statusMap = this.checkPackState(queryMap);
            if(statusMap!=null&&Double.valueOf(statusMap.get("el")+"")==0){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date now = format.parse(String.valueOf(statusMap.get("now")));
                    Date gatherTime = format.parse(String.valueOf(statusMap.get("gatherTime")));
                    Calendar cal = Calendar.getInstance();  
                    cal.setTime(now);    
                    long time1 = cal.getTimeInMillis();                 
                    cal.setTime(gatherTime);    
                    long time2 = cal.getTimeInMillis();         
                    long between_seconds=(time1-time2)/(1000);
                    if(between_seconds>60){
                      //最新记录存在掉电状态 
                        map.put("POWER_ON_STATUS", "下电");
                        //map.put("RUN_STATUS", "否");
                    }else {
                        map.put("POWER_ON_STATUS", "上电");
                    }
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else if(statusMap!=null&&Double.valueOf(statusMap.get("el")+"")!=0){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date now = format.parse(String.valueOf(statusMap.get("now")));
                    Date gatherTime = format.parse(String.valueOf(statusMap.get("gatherTime")));
                    Calendar cal = Calendar.getInstance();  
                    cal.setTime(now);    
                    long time1 = cal.getTimeInMillis();                 
                    cal.setTime(gatherTime);    
                    long time2 = cal.getTimeInMillis();         
                    long between_minutes=(time1-time2)/(1000*60);
                    if(between_minutes>10){
                      //最新记录存在掉电状态 
                        map.put("POWER_ON_STATUS", "下电");
                        //map.put("RUN_STATUS", "否");
                    }else {
                        map.put("POWER_ON_STATUS", "上电");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //最新记录不存在掉电状态 
            }else {
                //最新记录存在掉电状态 
                map.put("POWER_ON_STATUS", "下电");
                map.put("RUN_STATUS", "否");
            }
            String address = "";
            try {
                if ((null != map.get("LATITUDE") && !map.get("LATITUDE").toString().trim().equals(""))
                        && (null != map.get("LONGITUDE") && !map.get("LONGITUDE").toString().trim().equals(""))) {
                    double[] JWD = BaiduAPI.wgs2bd(Double.valueOf(map.get("LATITUDE").toString().trim()), Double.valueOf( map.get("LONGITUDE")
                            .toString().trim()));
                    address = BaiduAPI.DecodeLonLat(JWD[0], JWD[1]);
                }
            } catch (IOException e) {
            	e.printStackTrace();
            }
            map.put("ADDRESS", address);
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 监控电池实时采集点电压温度信息</p>
     * @param paramsMap 参数
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getPackChartInfo(Map<String, Object> paramsMap) throws DaoException {
        //结果集
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        /*
         * 检查是否具有电压报警
         */
        //Map<String, Object> alertInfoMap;
        //alertInfoMap = new HashMap<String, Object>();
        //alertInfoMap = this.checkPackAlertInfo(paramsMap);
        
        //单体最高电压 单体最低电压
        paramsMap.put("colClientId", paramsMap.get("clientId"));
        BigDecimal maxVol = new BigDecimal("100");
        BigDecimal minVol = new BigDecimal("0");
        List<Map<String, Object>> volStandardList = this.entityDao.findByProperty("com.broadtext.rms.basic.model.TtPackModel.getSingleVolStandard", paramsMap);
        if(volStandardList!=null&&volStandardList.size()>0){
            Map<String, Object> volStandardMap = volStandardList.get(0);
            if(volStandardMap!=null){
                if(StringUtils.isNotBlank(volStandardMap.get("singleMaxVol").toString())){
                    maxVol = new BigDecimal(volStandardMap.get("singleMaxVol").toString());
                }
                if(StringUtils.isNotBlank(volStandardMap.get("singleMinVol").toString())){
                    minVol = new BigDecimal(volStandardMap.get("singleMinVol").toString());
                }
            }
        }
        /*
         * 图表数据集
         */
        List<Map<String, Object>> charInfo;
        charInfo = new ArrayList<Map<String, Object>>();
        //Step1、该电池下包含模块
        List<String> noNums;
        noNums = this.ttPackDao.getNoNums("com.broadtext.rms.monitor.model.TtCellvoltageCurrent.getNoNums", paramsMap);
        if (null != noNums && !noNums.isEmpty()) {
            //Step2、查出模块号对应的电压温度信息
            for (int i = 0; i < noNums.size(); i++) {
                /*
                 * map集 用来存储每个组下面的core_no(key:groupNo) 电压信息(key:vol) 温度信息(key：temp)
                 */
                Map<String, Object> singlePackInfo;
                singlePackInfo = new HashMap<String, Object>();
                singlePackInfo.put("minVol", minVol);
                singlePackInfo.put("maxVol", maxVol);
                singlePackInfo.put("no", noNums.get(i));
                
                //查询实体
                TtCellvoltageCurrent volEntity;
                volEntity = new TtCellvoltageCurrent();
                volEntity.setColClientId(paramsMap.get("clientId").toString());
                volEntity.setPackCode(paramsMap.get("packCode").toString());
                volEntity.setGroupNo(noNums.get(i));
                
                //电压信息list
                List<TtCellvoltageCurrent> volList;
                volList = this.entityDao.findByProperty(
                        "com.broadtext.rms.monitor.model.TtCellvoltageCurrent.getVolList", volEntity);
                if (null != volList && !volList.isEmpty()) {
                    //电池编号信息
                    List<String> groupNoList;
                    groupNoList = new ArrayList<String>();
                    
                    /*
                     * 电压信息
                     */
                    List<BigDecimal> singleVolList;
                    singleVolList = new ArrayList<BigDecimal>();
                    //String maxVolFlag = "n";//是否具有高压标志 默认没有
                    //String minVolFlag = "n";//是否具有低压标志 默认没有
                    for (int j = 0; j < volList.size(); j++) {
                        groupNoList.add(volList.get(j).getGroupCoreNo());
                        singleVolList.add(volList.get(j).getSinglecoreVoltage());
                        //遍历是否具有高压，低压
                        /*if(volList.get(j).getSinglecoreVoltage().compareTo(maxVol)>0){
                            //该组存在最高单体电压
                            maxVolFlag = "y";
                        }
                        if(volList.get(j).getSinglecoreVoltage().compareTo(minVol)<0){
                            //该组存在最低单体电压
                            minVolFlag = "y";
                        }*/
                    }
                    String markPointFlag = ""; //峰值标志位 11：高压报警&&低压报警 10：高压报警 01：低压报警 00：没有报警
                    /*if("y".equals(maxVolFlag) && "y".equals(minVolFlag)){
                        markPointFlag = "11";
                    } else if("y".equals(maxVolFlag) && "n".equals(minVolFlag)){
                        markPointFlag = "10";
                    } else if("n".equals(maxVolFlag) && "y".equals(minVolFlag)){
                        markPointFlag = "01";
                    } else {
                        markPointFlag = "00";
                    }*/
                    
                    
                    /*if("yes".equals(alertInfoMap.get("highVolFlag").toString()) && "yes".equals(alertInfoMap.get("lowVolFlag").toString())) {
                        //高压低压报警同时存在
                        if("y".equals(maxVolFlag) && "y".equals(minVolFlag)){
                            markPointFlag = "11";
                        } else if("y".equals(maxVolFlag) && "n".equals(minVolFlag)){
                            markPointFlag = "10";
                        } else if("n".equals(maxVolFlag) && "y".equals(minVolFlag)){
                            markPointFlag = "01";
                        } else {
                            markPointFlag = "00";
                        }
                        
                    } else if("yes".equals(alertInfoMap.get("highVolFlag").toString()) && "no".equals(alertInfoMap.get("lowVolFlag").toString())){
                        //存在高压 不存在低压
                        if("y".equals(maxVolFlag)){
                            markPointFlag = "10";
                        } else {
                            markPointFlag = "00";
                        }
                    } else if("no".equals(alertInfoMap.get("highVolFlag").toString()) && "yes".equals(alertInfoMap.get("lowVolFlag").toString())){
                        //不存在高压 存在低压
                        if("y".equals(minVolFlag)){
                            markPointFlag = "01";
                        } else {
                            markPointFlag = "00";
                        }
                    } else {
                       //不存在报警
                        markPointFlag = "00";
                    }*/
                    
                    singlePackInfo.put("vol", singleVolList);
                    singlePackInfo.put("groupNo", groupNoList);
                    singlePackInfo.put("markpoint", markPointFlag);
                }
                //温度
                List<String> temList;
                temList = this.entityDao.findByProperty(
                    "com.broadtext.rms.monitor.model.TtSamplingpointTempCurrent.getTempList",
                        volEntity);
                singlePackInfo.put("temp", temList);
                charInfo.add(singlePackInfo);
                dataMap.put("chartInfo", charInfo);
            }
        }
        return dataMap;
    }

    /**
     * 
     * <p>Description: 检查报废状态</p>
     * @param ids 主键数组
     * @return 检查结果
     * @throws DaoException 异常
     */
    public Object checkFailureStatus(String[] ids) throws DaoException {
        return this.ttPackDao.checkFailureStatus(ids);
    }
    /**
     * 
     * <p>Description: 检查无效状态</p>
     * @param ids 主键数组
     * @return 结果集
     * @throws DaoException 异常
     */
    public Object checkEnableStatus(String[] ids) throws DaoException {
        return this.ttPackDao.checkEnableStatus(ids);
    }
     
    /**
     * 
     * <p>Description: 报废</p>
     * @param ids 主键数组
     * @param currentUser 当前用户
     * @throws DaoException 异常
     */
    public void setFailure(String[] ids, String currentUser) throws DaoException {
        this.ttPackDao.setFailure(ids, currentUser);
    }
    
    /**
     * 
     * <p>Description: 获取监控电池当前位置信息</p>
     * @param c 终端id
     * @param p 电池id
     * @return 电池位置信息
     * @throws DaoException 异常信息
     */
    @SuppressWarnings("unchecked")
    public PackLocationInfo findCurrentLocationInfo(String c, String p) throws DaoException {
        Map<String, Object> queryMap;
        queryMap = new HashMap<String, Object>();
        queryMap.put("packCode", p);
        queryMap.put("clientId", c);
        List<PackLocationInfo> dataList;
        dataList  = this.entityDao.findByQuery(
            "com.broadtext.rms.monitor.model.TtPackCurrent.findCurrentLocationInfo", queryMap);
        if (dataList != null && !dataList.isEmpty()) {
            if((null !=dataList.get(0).getLatitude()&& !dataList.get(0).getLatitude().trim().equals("")) && (null!=dataList.get(0).getLongitude() && !dataList.get(0).getLongitude().trim().equals(""))){
                try {
                    //gps转百度坐标
                    String address = "";
                    double[] JWD = BaiduAPI.wgs2bd(Double.valueOf(dataList.get(0).getLatitude().trim()), Double.valueOf(dataList.get(0).getLongitude().trim()));
                    dataList.get(0).setLatitude(String.valueOf(JWD[0]));
                    dataList.get(0).setLongitude(String.valueOf(JWD[1]));
                    address = BaiduAPI.DecodeLonLat(JWD[0], JWD[1]);
                    dataList.get(0).setAddress(address);
                    return dataList.get(0);
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            } 
        }
        return null;
    }
    
    
    /**
     * 
     * <p>Description: 获取历史位置列表</p>
     * @param map 查询条件
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    public List<PackLocationInfo> findHistoryLocationList(Map<String, Object> map) throws DaoException {
        List<PackLocationInfo> data;
        data = new ArrayList<PackLocationInfo>();
        List<PackLocationInfo> loList;
        if("history".equals(map.get("flag").toString()) ){
            //查询历史数据
            if(null != map.get("packCode")){
                //查询时间范围  selectTime 格式  时间范围yyyy-mm-dd hh:mm:ss - yyyy-mm-dd hh:mm:ss
                if(null != map.get("selectTime")){
                    map.put("zeroTime", map.get("selectTime").toString().substring(0, 19));
                    map.put("selectTime", map.get("selectTime").toString().substring(22));
                }
                loList = this.entityDao.findByQuery(HISTORY_MODEL_NAME+".findHistoryLocationListTwo", map);
            } else {
                loList = new ArrayList<PackLocationInfo>();
            }
        } else {
            loList = this.entityDao.findByQuery(HISTORY_MODEL_NAME+".findHistoryLocationList", map);
        }
        if(loList != null && !loList.isEmpty()){
            //根据经纬度转换成真实地理位置
            for (int i = 0; i < loList.size(); i++) {
                if((null != loList.get(i).getLatitude() && !loList.get(i).getLatitude().trim().equals("")) && (null != loList.get(i).getLongitude()) && !loList.get(i).getLongitude().trim().equals("")){
                    //gps转百度坐标
                    double[] JWD = BaiduAPI.wgs2bd(Double.valueOf(loList.get(i).getLatitude().trim()), Double.valueOf(loList.get(i).getLongitude().trim()));
                    loList.get(i).setLatitude(String.valueOf(JWD[0]));
                    loList.get(i).setLongitude(String.valueOf(JWD[1]));
                    data.add(loList.get(i)); 
                } 
            }
        }
        return data;
    }
    
    /**
     * 
     * <p>Description: 分页查询历史报警</p>
     * @param map 查询条件
     * @param pageBounds 分页
     * @return 结果集
     * @throws DaoException 异常
     */
    public EntityPageBean<Object> findHistoryWarningList(Map<String, Object> map, PageBounds pageBounds)
        throws DaoException {
        return this.ttPackDao.findHistoryWarningList(map, pageBounds);
    }
    
    /**
     * 
     * <p>Description: 分页查询 监控电池历史数据</p>
     * @param map 查询条件
     * @param pageBounds 分页
     * @return 结果
     * @throws DaoException 异常
     */
    public EntityPageBean<Object> findMonitorHistoryDataList(Map<String, Object> map, PageBounds pageBounds)
        throws DaoException {

        return this.ttPackDao.findMonitorHistoryDataList(map, pageBounds);
    }
    
    /**
     * 
     * <p>Description: 查询电池历史数据详情</p>
     * @param queryMap 查询条件 电池终端id+电池唯一序列号+采集时间
     * @return 结果集
     * @throws DaoException 异常
     * @throws ParseException 
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> findPackHistoryDataDetail(Map<String, Object> queryMap) throws DaoException, ParseException {
        Map<String, Object> map;
        map = this.ttPackDao.findPackHistoryDataDetail(
            HISTORY_MODEL_NAME+".findPackHistoryDataDetail", queryMap);
        //调用百度api 解析经纬度为实际地理位置
        if (null != map && !map.isEmpty()) {
            //处理累计运行时间
            List<PackRunTimeSpan> list;
            list = this.entityDao.findByQuery(HISTORY_MODEL_NAME+".getRunTimeList", queryMap);
            double count = 0;
            if(list != null && !list.isEmpty()){
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                Date gatherTime = sdf.parse(queryMap.get("gatherTimes").toString());
                for (int i = 0; i < list.size(); i++) {
                    if(i==0){
                        if(null == list.get(i).getEndTime()){
                            //掉电时间不存在 用采集时间减
                            count += (gatherTime.getTime() - list.get(i).getStartTime().getTime()) ;
                            //最新记录不存在掉电时间
                            map.put("POWER_ON_STATUS", "上电");
                        } else {
                            //如果掉电时间大于采集时间 用采集时间减
                            if(list.get(i).getEndTime().getTime() > gatherTime.getTime()){
                              count += (gatherTime.getTime() - list.get(i).getStartTime().getTime()) ;
                              //采集时间之前 属于上电状态
                              map.put("POWER_ON_STATUS", "上电");
                            } else {
                                //若果掉电时间小于采集时间 用掉时间减
                                count += (list.get(i).getEndTime().getTime() - list.get(i).getStartTime().getTime()) ;
                                map.put("POWER_ON_STATUS", "下电");
                                map.put("RUN_STATUS", "否");
                            }
                        }
                    } else {
                       if(null == list.get(i).getEndTime()){
                           count += (gatherTime.getTime() - list.get(i).getStartTime().getTime()) ;
                       } else {
                           count += (list.get(i).getEndTime().getTime() - list.get(i).getStartTime().getTime()) ; 
                       }
                    }
                }
            } else {
                map.put("POWER_ON_STATUS", "掉电");
                map.put("RUN_STATUS", "否");
            }
            DecimalFormat dcmFmt = new DecimalFormat("0.00");
            map.put("RUN_TIME_SPAN", dcmFmt.format(count/1000/60/60) +"(H)");
            String address = "";
            try {
                if ((null != map.get("LATITUDE") && !map.get("LATITUDE").toString().trim().equals(""))
                        && (null != map.get("LONGITUDE") && !map.get("LONGITUDE").toString().trim().equals(""))) {
                    double[] JWD = BaiduAPI.wgs2bd(Double.valueOf(map.get("LATITUDE").toString().trim()), Double.valueOf( map.get("LONGITUDE")
                            .toString().trim()));
                    address = BaiduAPI.DecodeLonLat(JWD[0], JWD[1]);
                }
            } catch (IOException e) {
            }
            map.put("ADDRESS", address);
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 查询电池历史数据 温度电压图表信息</p>
     * @param queryMap 查询条件
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> findEchartHistoryData(Map<String, Object> queryMap) throws DaoException {
        List<Map<String, Object>> charInfo;
        charInfo = new ArrayList<Map<String, Object>>();
        //单体最高电压 单体最低电压
        BigDecimal maxVol = new BigDecimal("100");
        BigDecimal minVol = new BigDecimal("0");
        List<Map<String, Object>> volStandardList = this.entityDao.findByProperty("com.broadtext.rms.basic.model.TtPackModel.getSingleVolStandard", queryMap);
        if(volStandardList!=null&&volStandardList.size()>0){
            Map<String, Object> volStandardMap = volStandardList.get(0);
            if(volStandardMap!=null){
                if(StringUtils.isNotBlank(volStandardMap.get("singleMaxVol").toString())){
                    maxVol = new BigDecimal(volStandardMap.get("singleMaxVol").toString());
                }
                if(StringUtils.isNotBlank(volStandardMap.get("singleMinVol").toString())){
                    minVol = new BigDecimal(volStandardMap.get("singleMinVol").toString());
                }
            }
        }
        //Step1、该电池下包含模块
        List<String> noNums;
        noNums = this.entityDao.findByQuery(
            "com.broadtext.rms.monitor.model.TtCellvoltageCurrent.getHistoryNoNums", queryMap);
        if (!noNums.isEmpty()) {
            //Step2、查出模块号对应的电压温度信息
            for (int i = 0; i < noNums.size(); i++) {
                //map集 用来存储每个组下面的core_no(key:groupNo) 电压信息(key:vol) 温度信息(key：temp)
                Map<String, Object> singlePackInfo;
                singlePackInfo = new HashMap<String, Object>();
                //电压标准值
                singlePackInfo.put("minVol", minVol);
                singlePackInfo.put("maxVol", maxVol);
                singlePackInfo.put("no", noNums.get(i));
                //查询
                queryMap.put("gNo", noNums.get(i));
                
                //电压信息list
                List<TtCellvoltageCurrent> volList;
                volList = this.entityDao.findByQuery(
                        "com.broadtext.rms.monitor.model.TtCellvoltageCurrent.getHistoryVolList", queryMap);
                if (!volList.isEmpty()) {
                    //电池编号信息
                    List<String> groupNoList;
                    groupNoList = new ArrayList<String>();
                    
                    String maxVolFlag = "n"; //是否具有高压标志 默认没有
                    String minVolFlag = "n"; //是否具有低压标志 默认没有
                    String markPointFlag = "";
                    //电压信息
                    List<BigDecimal> singleVolList;
                    singleVolList = new ArrayList<BigDecimal>();
                    for (int j = 0; j < volList.size(); j++) {
                        groupNoList.add(volList.get(j).getGroupCoreNo());
                        singleVolList.add(volList.get(j).getSinglecoreVoltage());
                        if(volList.get(j).getSinglecoreVoltage().compareTo(maxVol)>0){
                            //该组存在最高单体电压
                            maxVolFlag = "y";
                        }
                        if(volList.get(j).getSinglecoreVoltage().compareTo(minVol)<0){
                            //该组存在最低单体电压
                            minVolFlag = "y";
                        }
                    }
                    if("y".equals(maxVolFlag) && "y".equals(minVolFlag)){
                        markPointFlag = "11";
                    } else if("y".equals(maxVolFlag) && "n".equals(minVolFlag)){
                        markPointFlag = "10";
                    } else if("n".equals(maxVolFlag) && "y".equals(minVolFlag)){
                        markPointFlag = "01";
                    } else {
                        markPointFlag = "00";
                    }
                    singlePackInfo.put("vol", singleVolList);
                    singlePackInfo.put("groupNo", groupNoList);
                    singlePackInfo.put("markpoint", markPointFlag);
                }
                //温度
                List<String> temList;
                temList = this.entityDao.findByQuery(
                    "com.broadtext.rms.monitor.model.TtSamplingpointTempCurrent.getHistoryTempList",
                        queryMap);
                singlePackInfo.put("temp", temList);
                
                charInfo.add(singlePackInfo);
            }
        }
        return charInfo;
    }
    
    /**
     * 
     * <p>Description: 查询电池历史数据 温度电压图表信息</p>
     * @param queryMap 查询条件
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    public List<Map<String, Object>> findEchartHistoryData1(Map<String, Object> queryMap) throws DaoException {
        List<Map<String, Object>> charInfo;
        charInfo = new ArrayList<Map<String, Object>>();
        //单体最高电压 单体最低电压
        BigDecimal maxVol = new BigDecimal("100");
        BigDecimal minVol = new BigDecimal("0");
        List<Map<String, Object>> volStandardList = this.entityDao.findByProperty("com.broadtext.rms.basic.model.TtPackModel.getSingleVolStandard", queryMap);
        if(volStandardList!=null&&volStandardList.size()>0){
            Map<String, Object> volStandardMap = volStandardList.get(0);
            if(volStandardMap!=null){
                if(StringUtils.isNotBlank(volStandardMap.get("singleMaxVol").toString())){
                    maxVol = new BigDecimal(volStandardMap.get("singleMaxVol").toString());
                }
                if(StringUtils.isNotBlank(volStandardMap.get("singleMinVol").toString())){
                    minVol = new BigDecimal(volStandardMap.get("singleMinVol").toString());
                }
            }
        }
        //Step1、该电池下包含模块
        List<String> noNums;
        noNums = this.entityDao.findByQuery(
            "com.broadtext.rms.monitor.model.TtCellvoltageCurrent.getHistoryNoNums", queryMap);
        if (null != noNums && !noNums.isEmpty()) {
            ExecutorService exec = Executors.newCachedThreadPool();//工头
            ArrayList<Future<List<TtCellvoltageCurrent>>> results = new ArrayList<Future<List<TtCellvoltageCurrent>>>();//
            ArrayList<Future<List<String>>> results1 = new ArrayList<Future<List<String>>>();//
            //遍历电池组查询数据
            for (int i = 0; i < noNums.size(); i++) {
                //启动线程查询数据
                Map<String, Object> conCurrentMap = new ConcurrentHashMap<>();
                for (String key : queryMap.keySet()) {
                    conCurrentMap.put(key, queryMap.get(key));
                }
                conCurrentMap.put("gNo", noNums.get(i));
                StringBuffer queryVolsqlAlis = new StringBuffer("com.broadtext.rms.monitor.model.TtCellvoltageCurrent.getHistoryVolList");
                //查询电压数据线程
                QueryThread<TtCellvoltageCurrent> t = new QueryThread<TtCellvoltageCurrent>(conCurrentMap,entityDao,queryVolsqlAlis);
                StringBuffer queryTempsqlAlis = new StringBuffer("com.broadtext.rms.monitor.model.TtSamplingpointTempCurrent.getHistoryTempList");
                //查询温度数据线程
                QueryThread<String> t1 = new QueryThread<>(conCurrentMap, entityDao, queryTempsqlAlis);
                results.add(exec.submit(t));
                results1.add(exec.submit(t1));
            }
            for (int m = 0; m < results.size(); m++) {
                Future<List<TtCellvoltageCurrent>> future = results.get(m);
                Future<List<String>> tempFuture = results1.get(m);
                //电池编号信息
                List<String> groupNoList;
                groupNoList = new ArrayList<String>();
                //电压信息
                List<BigDecimal> singleVolList;
                singleVolList = new ArrayList<BigDecimal>();
                //map集 用来存储每个组下面的core_no(key:groupNo) 电压信息(key:vol) 温度信息(key：temp)
                Map<String, Object> singlePackInfo;
                singlePackInfo = new HashMap<String, Object>();
                //电压标准值
                singlePackInfo.put("minVol", minVol);
                singlePackInfo.put("maxVol", maxVol);
                boolean flag = true;
                while(flag){
                    if(future.isDone()){
                        flag = false;
                        try {
                            List<TtCellvoltageCurrent> volList = future.get();
                            future.cancel(true);
                            if (!volList.isEmpty()) {
                                singlePackInfo.put("no", volList.get(0).getGroupNo());
                                //System.out.println(volList.get(0).getGroupNo());
                                for (int j = 0; j < volList.size(); j++) {
                                    groupNoList.add(volList.get(j).getGroupCoreNo());
                                    singleVolList.add(volList.get(j).getSinglecoreVoltage());
                                }
                                singlePackInfo.put("vol", singleVolList);
                                singlePackInfo.put("groupNo", groupNoList);
                                List<String> temList = tempFuture.get();
                                singlePackInfo.put("temp", temList);
                                charInfo.add(singlePackInfo);
                            }
                            //温度
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                    
                }
                
            }
            exec.shutdown();
        }
        return charInfo;
    }
    
    /**
     * 
     * <p>Description:  电池历史数据  位置监控获取监控电池位置信息</p>
     * @param queryMap 查询条件
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    public PackLocationInfo findHistoryLocationInfo(Map<String, Object> queryMap) throws DaoException {
        List<PackLocationInfo> dataList;
        dataList  = this.entityDao.findByQuery(
            HISTORY_MODEL_NAME+".findHistoryLocationInfo", queryMap);
        List<PackLocationInfo> gpsInfoList = this.entityDao.findByQuery(
                HISTORY_MODEL_NAME+".findHistoryGpsInfo", queryMap);
        if (!gpsInfoList.isEmpty()) {
            if((null != gpsInfoList.get(0).getLatitude() && !gpsInfoList.get(0).getLatitude().trim().equals("")) && (null != gpsInfoList.get(0).getLongitude() && !gpsInfoList.get(0).getLongitude().trim().equals(""))){
                try {
                    //gps转百度坐标
                    String address = "";
                    double[] JWD = BaiduAPI.wgs2bd(Double.valueOf(gpsInfoList.get(0).getLatitude().trim()), Double.valueOf(gpsInfoList.get(0).getLongitude().trim()));
                    dataList.get(0).setLatitude(String.valueOf(JWD[0]));
                    dataList.get(0).setLongitude(String.valueOf(JWD[1]));
                    address = BaiduAPI.DecodeLonLat(JWD[0], JWD[1]);
                    dataList.get(0).setAddress(address);
                    return dataList.get(0);
                } catch (IOException e) {
                    e.printStackTrace();
                } 
            } 
        }
        return null;
    }
    
    @Override
    public Map<String, Object> dataBackToZip(String pkId, String sysuser) throws ServiceException {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        List<FileBean> fileList;
        fileList = new ArrayList<FileBean>();
        TtPackAlert alert;
        try {
            alert = (TtPackAlert) this.entityDao.findById(
                "com.broadtext.rms.monitor.model.TtPackAlert.selectByPrimaryKey", pkId);
            if (alert != null) {
                int prev;
                prev = Integer.valueOf(this.sysDictDao.selectDictByPro("ALERT_FILE_CONF", "1"));
                int after;
                after = Integer.valueOf(this.sysDictDao.selectDictByPro("ALERT_FILE_CONF", "2"));
                int waitTime;
                waitTime = Integer.valueOf(this.sysDictDao.selectDictByPro("ALERT_FILE_CONF", "3"));
                Date happenTime;
                happenTime = alert.getHappenTime();
                String path;
                File file = new File(alert.getOrigmsgPath());
                //获取文件的上层文件夹路径
                path = file.getParent() + StrUtil.FILE_SEPARATOR;
                SimpleDateFormat sdf;
                sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String preDate;
                preDate = StrUtil.ALERT_PATH_PREFIX + alert.getPackCode() + "_"
                    + sdf.format(new Date(happenTime.getTime() - prev * StrUtil.MILLISECOND));
                String afterDate;
                afterDate = StrUtil.ALERT_PATH_PREFIX + alert.getPackCode() + "_"
                    + sdf.format(new Date(happenTime.getTime() + after * StrUtil.MILLISECOND));
                //根据最长等待时间计算最多尝试次数
                long maxTry;
                maxTry = (long) (waitTime * StrUtil.MILLISECOND / StrUtil.TIME_INTERVAL);
                //时间范围内告警报文文件是否完整
                boolean fileOk = false;
                int temp = 0;
                //验证文件时间范围或超出最长等待时间
                while (temp < maxTry) {
                    temp ++;
                    fileOk = this.checkFileOk(path, afterDate);
                    if (fileOk) {
                        break;
                    }
                    try {
                        //间隔5秒执行一次
                        Thread.sleep(StrUtil.TIME_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                fileList = this.getAlertFileList(path, preDate, afterDate);
                if (fileList.size() == 0) {
                    //如果文件为空，返回
                    map.put(MSG, "FILE_EMPTY");
                    return map;
                }
                String zipPath;
                zipPath = this.sysDictDao.selectDictByPro("ALERT_FILE_CONF", "4");
                if ("".equals(StrUtil.strTrim(zipPath))) {
                    //数据库未配置路径
                    zipPath = StrUtil.ZIP_DEFAULT_PATH;
                }
                zipPath = this.getZipFilePath(zipPath, alert);
                ZipUtils.zipMultiFile(fileList, zipPath);
                //更新告警记录
                alert.setZipOrigmsgPath(zipPath);
                alert.setUpdateUser(sysuser);
                alert.setUpdateDate(new Date());
                this.entityDao.updateRecord("com.broadtext.rms.monitor.model.TtPackAlert.updateByPrimaryKey", alert);
            } else {
                map.put(MSG, "error");
                return map;
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        } catch (NumberFormatException e) {
            map.put(MSG, "error dict");
        }
        //查字典
        return map;
    }

    /**
     * 
     * <p>Description: 读取符合条件的文件</p>
     * @param path 路径
     * @param preDate 文件时间：初始
     * @param afterDate 文件时间：结束
     * @return 文件list
     */
    private List<FileBean> getAlertFileList(String path, String preDate, String afterDate) {
        List<FileBean> list;
        list = new ArrayList<FileBean>();
        FileBean bean;
        if (path != null && new File(path).exists()) {
            File file;
            file = new File(path);
            File[] files;
            files = file.listFiles();
            for (int i = 0; i < files.length; ++i) {
                String fileName;
                fileName = files[i].getName();
                if (fileName.compareTo(preDate) >= 0 && fileName.compareTo(afterDate) <= 0) {
                    bean = new FileBean();
                    bean.setFileName(fileName);
                    bean.setFilePath(path);
                    list.add(bean);
                }
            }
        }
        return list;
    }

    /**
     * 
     * <p>Description: 检验当前要下载的路径下时间范围内的文件是否完整</p>
     * @param path 路径
     * @param afterDate 文件时间：结束
     * @return 是否完整
     */
    private boolean checkFileOk(String path, String afterDate) {
        if (path != null && new File(path).exists()) {
            File file;
            file = new File(path);
            File[] files;
            files = file.listFiles();
            for (int i = 0; i < files.length; ++i) {
                String fileName;
                fileName = files[i].getName();
                if (fileName.compareTo(afterDate) >= 0) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 
     * <p>Description: 合成回传数据保存路径和文件名称</p>
     * @param zipPath 回传数据根目录路径
     * @param alert 告警信息实体
     * @return 路径及名称
     */
    private String getZipFilePath(String zipPath, TtPackAlert alert) {
        SimpleDateFormat sdf;
        sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdfTime;
        sdfTime = new SimpleDateFormat("yyyyMMddHHmmss");
        String date;
        date = sdf.format(alert.getHappenTime());
        String happenTime;
        happenTime = sdfTime.format(alert.getHappenTime());
        zipPath = zipPath + StrUtil.FILE_SEPARATOR + alert.getPackCode() + StrUtil.FILE_SEPARATOR
            + date + StrUtil.FILE_SEPARATOR + alert.getPackCode() + "_" + happenTime + StrUtil.ZIP_SUFFIX;
        return zipPath;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean checkUnhandled(String[] idArray) throws ServiceException {
        List<TtPackAlert> alertList;
        try {
            alertList = this.entityDao.findByProperty(
                "com.broadtext.rms.monitor.model.TtPackAlert.checkUnhandled", idArray);
            if (alertList.size() == 0) {
                return true;
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean checkUnneedhandled(String[] idArray) throws ServiceException {
        List<TtPackAlert> alertList;
        try {
            alertList = this.entityDao.findByProperty(
                "com.broadtext.rms.monitor.model.TtPackAlert.checkUnneedhandled", idArray);
            if (alertList.size() == 0) {
                return true;
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return false;
    }

    @Override
    public Map<String, Object> updateAlertHandled(String[] idArray, String handleType, String sysuser)
        throws ServiceException {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String type;
        if ("handled".equals(handleType)) {
            //已处理
            type = HANDLED;
        } else {
            //无需处理
            type = UNNEED_HANDLED;
        }
        TtPackAlert alert;
        for (String id : idArray) {
            try {
                alert = (TtPackAlert) this.entityDao.findById(
                    "com.broadtext.rms.monitor.model.TtPackAlert.selectByPrimaryKey", id);
                if (alert != null) {
                    alert.setHandleStatus(type);
                    alert.setUpdateDate(new Date());
                    alert.setUpdateUser(sysuser);
                    this.entityDao.updateRecord(
                        "com.broadtext.rms.monitor.model.TtPackAlert.updateByPrimaryKey", alert);
                } else {
                    map.put(MSG, "error");
                }
            } catch (DaoException e) {
                throw new ServiceException(e);
            }
        }
        map.put(MSG, true);
        return map;
    }

    @Override
    public String getAlertZipPath(String pkId) throws ServiceException {
        TtPackAlert alert;
        try {
            alert = (TtPackAlert) this.entityDao.findById(
                    "com.broadtext.rms.monitor.model.TtPackAlert.selectByPrimaryKey", pkId);
            if (alert != null) {
                return alert.getZipOrigmsgPath();
            }
        } catch (DaoException e) {
            throw new ServiceException(e);
        }
        return null;
    }
    
    /**
     * 
     * <p>Description: 历史轨迹列表轨迹查询</p>
     * @param map 查询条件
     * @param pageBounds 分页
     * @return 结果集
     * @throws DaoException 异常
     */
    public EntityPageBean<PackLocationInfo> findHistoryLocationListByPage(Map<String, Object> map, PageBounds pageBounds) throws DaoException {
        EntityPageBean<PackLocationInfo> pageBean;
        if("history".equals(map.get("flag").toString())){
            //查询历史数据
            if(null != map.get("packCode")){
                //查询时间范围 
                if(null != map.get("selectTime")){
                    map.put("zeroTime", map.get("selectTime").toString().substring(0, 19));
                    map.put("selectTime", map.get("selectTime").toString().substring(22));
                }
                pageBean = this.ttPackDao.findHistoryLocationListByPage(HISTORY_MODEL_NAME+".findHistoryLocationListTwo", map, pageBounds);
            } else {
                pageBean = null;
            }
        } else {
            pageBean = this.ttPackDao.findHistoryLocationListByPage(HISTORY_MODEL_NAME+".findHistoryLocationList", map, pageBounds);
        }
        if(null != pageBean && null != pageBean.getResults() && !pageBean.getResults().isEmpty()){
            List<PackLocationInfo> loList;
            loList = pageBean.getResults();
            for (int i = 0; i < loList.size(); i++) {
                    try {
                        //gps转百度坐标
                        String address = "";
                        if(!"".equals(loList.get(i).getLatitude()) && !"".equals(loList.get(i).getLongitude())){
                        	double[] JWD = BaiduAPI.wgs2bd(Double.valueOf(loList.get(i).getLatitude().trim()), Double.valueOf(loList.get(i).getLongitude().trim()));
                            loList.get(i).setLatitude(String.valueOf(JWD[0]));
                            loList.get(i).setLongitude(String.valueOf(JWD[1]));
                            address = BaiduAPI.DecodeLonLat(JWD[0], JWD[1]);
                            loList.get(i).setAddress(address);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } 
            }
            pageBean.setResults(loList);
        }
        return pageBean;
        
    }
    
    /**
     * 
     * <p>Description: 查询导出列表list</p>
     * @param map 结果集
     * @param response 响应 
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unchecked")
    public void findHistoryLocationExportList(Map<String, Object> map,  HttpServletResponse response) throws DaoException {
        List<PackLocationInfo> loList;
        if("history".equals(map.get("flag").toString()) ){
            //查询历史数据
            if(null != map.get("packCode")){
                //查询时间范围  selectTime 格式  时间范围yyyy-mm-dd hh:mm:ss - yyyy-mm-dd hh:mm:ss
                if(null != map.get("selectTime")){
                    map.put("zeroTime", map.get("selectTime").toString().substring(0, 19));
                    map.put("selectTime", map.get("selectTime").toString().substring(22));
                }
                loList = this.entityDao.findByQuery(HISTORY_MODEL_NAME+".findHistoryLocationListTwo", map);
            } else {
                loList = new ArrayList<PackLocationInfo>();
            }
        } else {
            loList = this.entityDao.findByQuery(HISTORY_MODEL_NAME+".findHistoryLocationList", map);
        }
        if(loList != null && !loList.isEmpty()){
                 ExportThread t;
                 t = new ExportThread(loList, "导出历史轨迹"+map.get("exportTime")+".xlsx");
                 t.run();
        }
    }
    
    /**
     * <p>Description: 检查电池是否具有高低压报警</p>
     * @param t 查询条件
     * @return 结果集
     * @throws DaoException 异常
     */
    @SuppressWarnings("unused")
    private Map<String, Object> checkPackAlertInfo(Map<String, Object> queryMap) throws DaoException {
        Map<String, Object> resultMap;
        resultMap = new HashMap<String, Object>();
        TtPackCurrent tpc;
        tpc = this.ttPackDao.getTtPackCurrentById(queryMap);
        if(null != tpc) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            queryMap.put("gatherTimes", formatter.format(tpc.getGatherTime()));
            //未处理  高压 code W004
            queryMap.put("alertCode", "W004");
            String highVol = "";
            highVol = this.ttPackDao.countAlertInfo(queryMap);
            if(null != highVol && "yes".equals(highVol)){
                //存在高压报警
                resultMap.put("highVolFlag", "yes");
            } else {
                resultMap.put("highVolFlag", "no");
            }
            //未处理 低压 code W006
            queryMap.put("alertCode", "W006");
            String lowVol = "";
            lowVol = this.ttPackDao.countAlertInfo(queryMap);
            if(null != lowVol && "yes".equals(lowVol)){
                //存在低压报警
                resultMap.put("lowVolFlag", "yes");
            } else {
                resultMap.put("lowVolFlag", "no");
            }
            return resultMap;
        } else {
            return null;
        }
    }
    
    /**
     * 
     * <p>Description: 检查掉电状态</p>
     * @param params 查询条件
     * @return 结果
     * @throws DaoException 异常
     */
    public Object checkPowerFailStatus(Map<String, Object> params) throws DaoException {
        return this.ttPackDao.checkPowerFailStatus(params);
    }
    
    /**
     * 
     * <p>Description: 检查离线文件是否已经上传过</p>
     * @param fileNameLists 离线文件名list
     * @return 结果集
     * @throws DaoException 异常
     */
    public Object checkOfflineFileExist(List<String> fileNameLists) throws DaoException {
        return this.ttPackDao.checkOfflineFileExist(fileNameLists);
    }
    
    /**
     * 
     * <p>Description: 调用WCF服务</p>
     * @param request 请求
     * @param dataList 报文信息
     * @param files 文件
     * @return 调用结果
     * @throws DaoException 异常
     */
    public Object callWCFService(HttpServletRequest request, List<String> dataList, MultipartFile[] files) throws DaoException {
        String resultInfo = "";
        //调用服务
        resultInfo = SaveMsgDataClient.saveMsgData(dataList);
        if(!"success".equals(resultInfo)){
            return resultInfo;
        } else {
           //成功后执行文件上传 
            String savePath = "";
            try {
                savePath = this.sysDictDao.selectDictByPro("OFFLINE_FILE_PATH", "1");
            } catch (DaoException e) {
                e.printStackTrace();
            }
            if ("".equals(StrUtil.strTrim(savePath))) {
                //数据库未配置路径
                savePath = StrUtil.OFFLINE_MESSAGE_PATH;
            }
            for (int i = 0; i < files.length; i++) {
                File fileIn = null;
                fileIn = new File(savePath);
                //判断上传文件的保存目录是否存在
                if (!fileIn.exists() && !fileIn.isDirectory()) {
                    //创建目录
                    fileIn.mkdirs();
                }
                String filePath = savePath + File.separator + files[i].getOriginalFilename();
                //拿到输出流，同时重命名上传的文件  
                FileOutputStream os = null;
                ByteArrayInputStream ba = null;
                try {
                    os = new FileOutputStream(filePath);
                    //拿到上传文件的输入流  
                    ba = (ByteArrayInputStream) files[i].getInputStream();
                    //以写字节的方式写文件  
                    int b = 0;  
                    while((b=ba.read()) != -1){  
                        os.write(b);  
                    }  
                } catch (IOException e) {
                    e.printStackTrace();
                }  finally{
                    try {
                        os.flush();
                        os.close();  
                        ba.close(); 
                    } catch (IOException e) {
                        e.printStackTrace();
                    }  
                }
                //更新离线报文表信息
                Map<String, Object> insertMap;
                insertMap = new HashMap<String, Object>();
                insertMap.put("fileName", files[i].getOriginalFilename());
                insertMap.put("pkId", UUIDUtils.getUUID());
                insertMap.put("filePath", filePath);
                insertMap.put("createUser", String.valueOf(request.getSession().getAttribute("sys.userName")));
                this.entityDao.insertRecord("com.broadtext.rms.monitor.model.TtPack.insertOffline", insertMap);
            }
        }
        return resultInfo;
    }
    
    /**
     * 获取电子围栏位置信息
     * @param c 终端Id
     * @param p 电池Id
     * @return 结果集
     * @throws DaoException 
     */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getEfenceInfo(String c, String p) throws DaoException {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<>();
		params.put("clientId", c);
		params.put("packCode", p);
		List<Map<String, Object>> gpsInfoMap;
		gpsInfoMap = this.entityDao.findByQuery("com.broadtext.rms.monitor.model.TtPack.getEfenceGpsInfo", params);
		dataMap.put("gpsInfo", gpsInfoMap);
		return dataMap;
	}
	
	/**
	 * 保存电子围栏数据
	 * @param dataList 参数
	 * @throws DaoException 异常
	 */
	public void saveEfenceInfo(List<FenceGpsInfo> dataList) throws DaoException {
		this.ttPackDao.deleteFenceInfo(dataList);
	}

    /** (non-Javadoc)
     * <p>Title: checkPackState</p>
     * <p>Description: </p>
     * @param params
     * @return
     * @throws DaoException
     * @see com.broadtext.rms.monitor.service.IPackDataMonitorService#checkPackState(java.util.Map)
     */
	@SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> checkPackState(Map<String, Object> params) throws DaoException {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Map<String,Object> map = new HashMap<String, Object>();
        list = this.entityDao.findByProperty("com.broadtext.rms.monitor.model.TtPack.checkPackState", params);
        if(list!=null&&list.size()>0){
            map = list.get(0);
        }
        return map;
    }
	
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Date gatherTime = new Date();
        try {
            now = format.parse("2017-11-09 11:11:11");
            gatherTime = format.parse("2017-11-09 11:12:10");
            Calendar cal = Calendar.getInstance();    
            cal.setTime(now);    
            long time1 = cal.getTimeInMillis();                 
            cal.setTime(gatherTime);    
            long time2 = cal.getTimeInMillis();         
            long between_days=(time2-time1)/(1000);
            System.out.println(between_days);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

    @Override
    public Map<String, Object> getPackCode() throws DaoException {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Map<String,Object> map = new HashMap<String, Object>();
        list = this.entityDao.findByProperty("com.broadtext.rms.monitor.model.TtPackCurrent.getPackCode",null);
        if(list!=null&&list.size()>0){
            map = list.get(0);
        }
        return map;
    }
}
